package framework.ui;

import org.openems.entity.Entity;
import org.openems.entity.Key;
import org.openems.entity.TraceEntity;

import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import framework.DomainService;
import framework.EntityStoreListener;

public class EmsLineChartConnector {
	public EmsLineChartConnector(final LineChart<Number, Number> chart, DomainService service,
			final Key key) {
		
		TraceEntity entity = (TraceEntity)service.getEntity(key);
		
		chart.getYAxis().setLabel(entity.getVerticalAxisName());
		chart.getXAxis().setLabel(entity.getHorizontalAxisName());
		chart.getYAxis().setAutoRanging(true);
		chart.getXAxis().setAutoRanging(false);
		service.addEntityStoreListener(new EntityStoreListener() {
			@Override
			public void valueChanged(Entity entity) {
				updateChart((TraceEntity)entity, chart);
			}			
		}, key);
	}

	protected void updateChart(TraceEntity entity, LineChart<Number, Number> chart) {
		XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();
		
		Double xstep = entity.getHorizontalMax() / (double)entity.getData().length;
		double mag = 1.0;
		double step = (double)entity.getData().length / chart.getWidth()/mag;
        for (int i = 0; i < chart.getWidth() * mag; i++) {
        	int ii = (int)(i * step);
            double y = entity.getData()[ii];
            double x = entity.getHorizontalMin() + xstep * (double)(ii);
            series.getData().add(new XYChart.Data<Number, Number>(x, y));
        }
        ((NumberAxis)chart.getXAxis()).setLowerBound(entity.getHorizontalMin());
        ((NumberAxis)chart.getXAxis()).setUpperBound(entity.getHorizontalMax());
        chart.getData().clear();
        chart.createSymbolsProperty().set(false);
        chart.animatedProperty().set(false);
        chart.getData().add(series);
        chart.setEffect(null);
        chart.getData().get(0).getNode().setStyle("-fx-stroke-width:1");	
    }
}
